package cn.com.jsr.translation.termidentifier.tool;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.jsr.translation.termidentifier.Seeker;

/**
 * 批量处理工具
 */
public class BatchReplacer{
	static Logger logger = LoggerFactory.getLogger(BatchReplacer.class);
	
	/**
	 * 批量对指定的目录下的所有文件进行处理
	 * @param seeker 术语处理器
	 * @param dir 批量处理的目录
	 * @param filenameFilter 文件过滤器
	 * @param recursive 是否递归处理
	 * @throws IOException 
	 */
	public static void replace(Seeker seeker, File dir, FilenameFilter filenameFilter, boolean recursive) throws IOException{
		if(!dir.isDirectory()){
			logger.warn("Target is not a valid directory or does not exist: {}", dir.getAbsolutePath());
			
			return;
		}
		
		/* 文件处理 */
		File[] files = dir.listFiles(filenameFilter);
		for(File file: files){
			/* 如果是目录，则递归处理 */
			if(file.isDirectory() && recursive)
				replace(seeker, file, filenameFilter, recursive);
			
			/* 拷贝文件，生成副本 */
			Path srcPath = Paths.get(file.toURI());
			File bakFile = new File(file.getAbsolutePath() + ".bak");
			Files.copy(srcPath, Paths.get(bakFile.toURI()), StandardCopyOption.REPLACE_EXISTING);
			/* 更新源文件 */
			byte[] contentBytes = Files.readAllBytes(srcPath);
			String content = new String(contentBytes, "UTF-8");
			content = seeker.seek(content);
			Files.write(srcPath, content.getBytes());
		}
	}
	/**
	 * 以递归方式批量对指定目录下的所有.txt文件进行处理
	 * @param seeker 术语处理器
	 * @param dir批量处理的目录
	 * @throws IOException 
	 */
	public static void replace(Seeker seeker, File dir) throws IOException{
		replace(seeker, dir, new FilenameFilter(){
			@Override
			public boolean accept(File dir, String name){
				return name.toLowerCase().endsWith(".txt");
			}
		}, true);
	};
}
